//
//  MainViewController.m
//  Mp4Writer
//
//  Created by zjp on 2021/8/23.
//

#import "MainViewController.h"
#import <TXLiteAVSDK_TRTC/TRTCCloud.h>
#import "Debug/GenerateTestUserSig.h"
#import "RoomData.h"
#import "RemoteRecord/TRTCRemoteRecorder.h"
#import "FileUtils.h"

@interface MainViewController () <TRTCCloudDelegate, TRTCVideoRenderDelegate, TRTCVideoFrameDelegate, TRTCAudioFrameDelegate, TRTCRemoteRecorderDelegate>

@property (weak, nonatomic) IBOutlet UIView *localView;
@property (weak, nonatomic) IBOutlet UIView *remoteView;
@property (weak, nonatomic) IBOutlet UIButton *startRecordBtn;
@property (weak, nonatomic) IBOutlet UIButton *endRecordBtn;

@property (nonatomic) TRTCCloud* trtcCloud;
@property (nonatomic, strong) TRTCRemoteRecorder *recorder;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.recorder = [[TRTCRemoteRecorder alloc] init];
    
    // Do any additional setup after loading the view.
    
    [self clearFile];
    
    [self setupTRTCCloud];
    self.remoteView.hidden = YES;
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    NSString* str = (NSString*)sender;
    NSLog(@"%@", str);
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    NSLog(@"viewDidDisappear");
    
    [self destroyTRTCCloud];
}

#pragma mark - TRTCCloud

- (void)setupTRTCCloud {
    [TRTCCloud setLogLevel:TRTCLogLevelDebug];
    [TRTCCloud setConsoleEnabled:YES];
    
    self.trtcCloud = [TRTCCloud sharedInstance];
    
    self.trtcCloud.delegate = self;
    
    [self.trtcCloud setAudioFrameDelegate:self];
    
    [self.trtcCloud startLocalPreview:YES view:self.localView];
    
    TRTCParams *params = [TRTCParams new];
    params.sdkAppId = SDKAppID;
    params.roomId = [[RoomData sharedInstance].roomid intValue];
    params.userId = [RoomData sharedInstance].userid;
    params.role = TRTCRoleAnchor;
    params.userSig = [GenerateTestUserSig genTestUserSig:params.userId];
    
    [self.trtcCloud enterRoom:params appScene:TRTCAppSceneVideoCall];
    
    TRTCVideoEncParam *videoEncParam = [TRTCVideoEncParam new];
    
    videoEncParam.videoResolution = TRTCVideoResolution_1920_1080;
    videoEncParam.videoBitrate = 1500;
    videoEncParam.videoFps = 15;
    
    [self.trtcCloud setVideoEncoderParam:videoEncParam];
    [self.trtcCloud startLocalAudio:TRTCAudioQualityDefault];
}

- (void)destroyTRTCCloud {
    [self.trtcCloud stopLocalPreview];
    [self.trtcCloud exitRoom];
    [TRTCCloud destroySharedIntance];
    _trtcCloud = nil;
}

#pragma mark - TRTCCloudDelegate

- (void)onEnterRoom:(NSInteger)result {
    
}

- (void)onExitRoom:(NSInteger)reason {
    
}

- (void)onUserVideoAvailable:(NSString *)userId available:(BOOL)available {
    if (available) {
        self.remoteView.hidden = NO;
        [self.trtcCloud startRemoteView:userId streamType:TRTCVideoStreamTypeBig view:self.remoteView];
        int suc = [self.trtcCloud setRemoteVideoRenderDelegate:userId delegate:self pixelFormat:TRTCVideoPixelFormat_NV12 bufferType:TRTCVideoBufferType_PixelBuffer];
        printf("suc: %d", suc);
    }
//    else {
//        self.remoteView.hidden = YES;
//        [self.trtcCloud stopRemoteView:userId streamType:TRTCVideoStreamTypeBig];
//    }
}

- (void)onRenderVideoFrame:(TRTCVideoFrame * _Nonnull)frame userId:(NSString* __nullable)userId streamType:(TRTCVideoStreamType)streamType {
    printf("onRenderVideoFrame width:%u height:%u pts:%llu \n", frame.width, frame.height, frame.timestamp);
    NSLog(@"%f", [[NSDate date] timeIntervalSince1970]);
    [self.recorder pushVideoFrame:frame];
    NSLog(@"%f", [[NSDate date] timeIntervalSince1970]);
    
    size_t size = CVPixelBufferGetDataSize(frame.pixelBuffer);
    CVPixelBufferLockBaseAddress(frame.pixelBuffer, 0);
    void *address = CVPixelBufferGetBaseAddress(frame.pixelBuffer);
    [FileUtils appendDocumentsFile:@"pixelBuffer.hop" buffer:address size:size];
    CVPixelBufferUnlockBaseAddress(frame.pixelBuffer, 0);
    


//    static NSFileHandle *h264FileHandle = NULL;
//    if (!h264FileHandle) {
//        NSString *remoteH264 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/trtc_record.yuv"];
//        NSFileManager *fileManager = [NSFileManager defaultManager];
//        //文件存在的话先删除文件
//        if ([fileManager fileExistsAtPath:remoteH264]) {
//            [fileManager removeItemAtPath:remoteH264 error:nil];
//        }
//        BOOL success = [fileManager createFileAtPath:remoteH264 contents:nil attributes:nil];
//        if (!success) {
//            printf("创建文件失败");
//            return;
//        }
//        h264FileHandle = [NSFileHandle fileHandleForWritingAtPath:remoteH264];
//
//        if (!h264FileHandle) {
//            printf("创建H264文件句柄失败");
//            return;
//        }
//    }
//    NSError *error = NULL;
//    if (@available(iOS 13.0, *)) {
//        [h264FileHandle writeData:[NSData dataWithBytes:frame.data.bytes length:frame.data.length] error:&error];
//    } else {
//        // Fallback on earlier versions
//    }
//    if (error) {
//        printf("存储文件失败");
//    }
}

- (void)onRemoteUserAudioFrame:(TRTCAudioFrame *)frame userId:(NSString *)userId {
    printf("onRemoteUserAudioFrame userid:%s sampleRate:%ld channels:%u pts:%llu cur:%f\n", userId.UTF8String, (long)frame.sampleRate, frame.channels, frame.timestamp, [[NSDate date] timeIntervalSince1970] * 1000);
    frame.timestamp = 0;
    [self.recorder pushAudioFrame:frame];
}

- (IBAction)startRecordAction:(id)sender {
    
    NSString *mp4Path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"record-%@.mp4", [NSDate date]]];
    TRTCRecordConfig *config = [[TRTCRecordConfig alloc] init];
    config.filePath = mp4Path;
    [self.recorder setConfig:config];
    [self.recorder startRecord];
    self.startRecordBtn.backgroundColor = [UIColor lightGrayColor];
}

- (IBAction)endRecordAction:(id)sender {
    [self.recorder stopRecord];
    self.startRecordBtn.backgroundColor = [UIColor lightGrayColor];
}

- (void)onFirstVideoFrame:(NSString *)userId streamType:(TRTCVideoStreamType)streamType width:(int)width height:(int)height {
    
}

- (TRTCRemoteRecorder *)recorder {
    if (!_recorder) {
        _recorder = [[TRTCRemoteRecorder alloc] init];
        _recorder.delegate = self;
        NSString *mp4Path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"record.mp4"];
        TRTCRecordConfig *config = [[TRTCRecordConfig alloc] init];
        config.filePath = mp4Path;
        [_recorder setConfig:config];
        [_recorder setDelegate:self];
    }
    return _recorder;
}

#pragma Mp4RecorderDelegate


- (void)onRemoteRecordEvent:(TRTCRemoteRecordEvent)event detail:(id)detail {
    NSLog(@"onRemoteRecordEvent:%lu:%@", (unsigned long)event, detail);
}


- (void)clearFile
{
    NSString * cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSArray * files = [[NSFileManager defaultManager ] subpathsAtPath:cachePath];
    //NSLog ( @"cachpath = %@" , cachePath);
    for ( NSString * p in files) {
        
        NSError * error = nil ;
        //获取文件全路径
        NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager ] fileExistsAtPath:fileAbsolutePath]) {
            [[NSFileManager defaultManager ] removeItemAtPath:fileAbsolutePath error :&error];
        }
    }
}

@end
